    package com.atelier.plugin.database.ui;

    import com.atelier.plugin.database.action.AddConnectionToListAction;
    import com.atelier.plugin.database.action.MysqlConnection;
    import com.atelier.plugin.database.action.RemoveConnectionAction;
    import com.atelier.plugin.database.domain.DatabaseConnectionInfo;
    import com.atelier.plugin.database.domain.DatabaseType;
    import com.atelier.plugin.database.domain.TableInfo;
    import com.atelier.plugin.database.util.ActionUtil;
    import com.atelier.plugin.database.util.ConnectionUtil;
    import com.atelier.plugin.projectWizard.util.ICONS;
    import com.atelier.plugin.service.DataBaseConnectionStorageService;
    import com.atelier.plugin.tool.ProjectUtils;
    import com.intellij.icons.AllIcons;
    import com.intellij.openapi.actionSystem.ActionToolbar;
    import com.intellij.openapi.actionSystem.AnAction;
    import com.intellij.openapi.actionSystem.AnActionEvent;
    import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
    import com.intellij.openapi.project.Project;
    import com.intellij.openapi.ui.TextFieldWithBrowseButton;
    import com.intellij.ui.components.JBList;
    import lombok.Data;
    import lombok.Getter;
    import net.sf.cglib.beans.BeanCopier;
    import org.jetbrains.annotations.NotNull;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.plaf.SplitPaneUI;
    import javax.swing.plaf.basic.BasicSplitPaneDivider;
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.List;

    public class DataSourceSettingDialog extends JDialog {
        public static Logger LOGGER=  LoggerFactory.getLogger(DataSourceSettingDialog.class);
        private JPanel contentPane;

        private JSplitPane jSplitPane;
        private JPanel dataSourcePanel;
        private JPanel dataSourceListPanel;
        private JTextField nameTextField;
        private JPanel dataSourceSettingDetailPanel;
        private JPanel settingCard1;
        private JTextField hostTextFiled;
        private JTextField portTextField;
        private JTextField userTextField;
        private JPasswordField passwordTextField;

        public TextFieldWithBrowseButton databaseTextFiled;
        private JTextField urlTextFiled;
        private JPanel connectionToolPanel;
        private JLabel testConnection;
        @Getter
        private JBList datasouceList;
        private ActionToolbarImpl actionToolbarImpl;
        private JLabel databaseLabel;
        private boolean isScaled = false;
        private JToggleButton scaleButton;
        private static final String IDEA ="IDEA";
        private static final String DATASOURCE="DATA SOURCES";
        private DatabaseType databaseType;
        private static DataSourceSettingDialog instance;

        @Getter
        private DefaultListModel<DatabaseConnectionInfo> listModel;
        public DataSourceSettingDialog() {
            databaseLabel.setText("  Database");
            setContentPane(contentPane);
            setModal(true);
            initUI();
            databaseTextFiled.setButtonIcon(AllIcons.Actions.GC);
            //=====================
            setTitle(DATASOURCE);
            // 设置分隔符位置（可以根据需要调整初始位置）
            jSplitPane.setDividerLocation(200);

            // 设置分隔器大小
            jSplitPane.setDividerSize(2); // 这里设置分隔器的大小为5像素

            //设置底部边框（通常jSplitPane没有底部边框）
            jSplitPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Colors.BLACK)); // 添加底部边框
            // 获取分隔器
            jSplitPane.setUI(new BasicSplitPaneUI()
            {
                @Override
                public BasicSplitPaneDivider createDefaultDivider()
                {
                    return new BasicSplitPaneDivider(this)
                    {
                        public void setBorder(Border b) {}

                        @Override
                        public void paint(Graphics g)
                        {
                            g.setColor(Colors.BLACK);
                            g.fillRect(0, 0, getSize().width+1, getSize().height+1);
                            super.paint(g);
                        }
                    };
                }
            });

            dataSourcePanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0,Colors.BLACK));
      }

        private void initUI() {
            Project project = ProjectUtils.getCurrProject();
            // 保存原始文本
            String originalText = testConnection.getText();
            testConnection.setText("<html><font color='#0077BB'>" + originalText + "</font></html>");
            testConnection.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            // 添加窗口关闭事件监听器

            testConnection.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {

                    //参数封装
                    try {
                        DatabaseConnectionInfo info = new DatabaseConnectionInfo();
                        info.setUsername(userTextField.getText());
                        info.setPassword(passwordTextField.getText());
                        info.setHost(hostTextFiled.getText());
                        info.setPort(portTextField.getText());
                        info.setDatabaseName(databaseTextFiled.getText());
                        info.setDatabaseType(databaseType);
                        ConnectionUtil instance = ConnectionUtil.getInstance(info);
                        if(instance.testConnection()) {
                            // 处理点击事件，例如打开链接
                            JOptionPane.showMessageDialog(null, "Connection Succeeded");
                            List<TableInfo> tableInfos = instance.fetchDatabaseInfo();
                            LOGGER.info("succeed");
                        }else{
                            JOptionPane.showMessageDialog(null, "Connection fail");
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Connection fail" +
                                "/r"+ex.getMessage());
                        //java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
                        throw new RuntimeException(ex.getMessage());
                    }

                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    // 鼠标进入时改变颜色
                    testConnection.setText("<html><u><font color='0077BB'>" + originalText + "</font></u></html>");
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    // 鼠标退出时恢复颜色
                    testConnection.setText("<html><font color='#0077BB'>" + originalText + "</font></html>");
                }
            });


            // 获取数据库连接信息列表
            List<DatabaseConnectionInfo> connectionInfos = DataBaseConnectionStorageService.getInstance(project).getConnectionInfos();
            ActionToolbar actionToolbar = ActionUtil.createActionToolbar("MyActionToolbarLocation", true, "com.atelier.plugin.action.database.menuGroup");
            JComponent component = actionToolbar.getComponent();
            // 创建一个 DefaultListModel 来显示连接信息
             listModel = new DefaultListModel<>();
             //创建新数据源避免修改原本数据源对象的数据
            for (DatabaseConnectionInfo connectionInfo : connectionInfos) {
                DatabaseConnectionInfo newConnectionInfo = new DatabaseConnectionInfo();
                BeanCopier beanCopier = BeanCopier.create(DatabaseConnectionInfo.class, DatabaseConnectionInfo.class, false);
                beanCopier.copy(connectionInfo, newConnectionInfo, null);
                listModel.addElement(newConnectionInfo);
            }
            datasouceList.setCellRenderer(new DatabaseConnectionListCellRenderer());
            // 添加 JList 到 dataSourceListPanel
            datasouceList.setModel(listModel);

            // 注册连接列表变化监听器
//            DataBaseConnectionStorageService.getInstance(project).addConnectionListChangeListener(newConnectionList -> {
//                if (newConnectionList != null&&!newConnectionList.isEmpty()) {
//                    // 刷新 listModel
//                    listModel.clear();
//                    for (DatabaseConnectionInfo connectionInfo : newConnectionList) {
//                        listModel.addElement(connectionInfo);
//                    }
//                    LOGGER.info("addConnectionListChangeListener");
//                    System.out.println(111);
//                }
//                datasouceList.setModel(listModel);
//            });
            // 添加选择事件监听器到 datasouceList

            datasouceList.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                        // 获取所选的连接信息对象
                        DatabaseConnectionInfo selectedConnectionInfo = (DatabaseConnectionInfo) datasouceList.getSelectedValue();
                        if (selectedConnectionInfo != null) {
                            // 这里可以访问连接信息对象的属性
                            String username = selectedConnectionInfo.getUsername();
                            String password = selectedConnectionInfo.getPassword();
                            String host = selectedConnectionInfo.getHost();
                            String port = selectedConnectionInfo.getPort();
                            String databaseName = selectedConnectionInfo.getDatabaseName();
                            String name = selectedConnectionInfo.getName();
                            String url = selectedConnectionInfo.getUrl();
                            urlTextFiled.setText(url);
                            nameTextField.setText(name);
                            databaseType = selectedConnectionInfo.getDatabaseType();
                            // 更新UI，将属性显示在相应的文本框中
                            userTextField.setText(username);
                            passwordTextField.setText(password);
                            hostTextFiled.setText(host);
                            portTextField.setText(port);
                            databaseTextFiled.setText(databaseName);
                            if(databaseType.equals(DatabaseType.MYSQL)){
                                databaseLabel.setText("  DataBase");
                            }else if(databaseType.equals(DatabaseType.ORACLE)){
                                databaseLabel.setText("  SID");
                            }
                        }
                    }
                }
            });
            datasouceList.enableInputMethods(true);


            //文本监听器
            // 添加文本框监听器，以便在用户修改文本框的值时更新连接信息对象和listModel
            bindTextFieldToConnectionInfo(hostTextFiled, "Host");
            bindTextFieldToConnectionInfo(userTextField, "UserName");
            bindTextFieldToConnectionInfo(portTextField, "Port");
            bindTextFieldToConnectionInfo(passwordTextField, "Password");
            bindTextFieldToConnectionInfo(databaseTextFiled.getTextField(), "Database");
            bindTextFieldToConnectionInfo(urlTextFiled, "URL");
            bindTextFieldToConnectionInfo(nameTextField, "Name");
        }
        public static DataSourceSettingDialog getInstance() {
            if (instance == null) {
                instance = new DataSourceSettingDialog();
            }
            return instance;
        }


        private void createUIComponents() {
            // 在这里创建自定义组件并将其分配给相应的变量
            Project project = ProjectUtils.getCurrProject();
            RemoveConnectionAction removeConnectionAction = new RemoveConnectionAction(this);

            //工具栏填充..
             actionToolbarImpl= (ActionToolbarImpl) ActionUtil.createActionToolbar("MyActionToolbarListLocation", true,
                     new AddConnectionToListAction("Add", "Add",AllIcons.General.Add),
                     removeConnectionAction
             );
             actionToolbarImpl.setTargetComponent(contentPane);
        }
        private void bindTextFieldToConnectionInfo(JTextField textField, String propertyName) {
            textField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    DatabaseConnectionInfo selectedConnectionInfo = (DatabaseConnectionInfo) datasouceList.getSelectedValue();
                    if (selectedConnectionInfo != null) {
                        switch (propertyName) {
                            case "Host":
                                selectedConnectionInfo.setHost(textField.getText());
                                break;
                            case "UserName":
                                selectedConnectionInfo.setUsername(textField.getText());
                                break;
                            case "Port":
                                selectedConnectionInfo.setPort(textField.getText());
                                break;
                            case "Password":
                                selectedConnectionInfo.setPassword(textField.getText());
                                break;
                            case "Database":
                                selectedConnectionInfo.setDatabaseName(textField.getText());
                                break;
                            case "Name":
                                selectedConnectionInfo.setName(textField.getText());
                                break;
                            case "URL":
                                selectedConnectionInfo.setUrl(textField.getText());
                        }

                        // 更新listModel中的元素，以便显示最新的值
                        listModel.setElementAt(selectedConnectionInfo, datasouceList.getSelectedIndex());
                    }
                }
            });
        }

        public void setDatasouceList(JBList datasouceList) {
            this.datasouceList = datasouceList;
        }

        public void setListModel(DefaultListModel<DatabaseConnectionInfo> listModel) {
            this.listModel = listModel;
        }

        public JLabel getDatabaseLabel() {
            return databaseLabel;
        }

        public void setDatabaseLabel(JLabel databaseLabel) {
            this.databaseLabel = databaseLabel;
        }
    }
